from PIL import Image
import numpy as np
from skimage.metrics import structural_similarity as ssim
from io import BytesIO


# NOTE:
# 可用, 但不建议用, llm在cv还没做, 先放这, 有总比没有好


def load_image_from_path(image_path):
    """从路径加载图像"""
    return Image.open(image_path)


def load_image_from_bytes(image_data):
    """从二进制数据加载图像"""
    return Image.open(BytesIO(image_data))


def resize_images(img1, img2):
    # 获取图片尺寸
    width1, height1 = img1.size
    width2, height2 = img2.size
    # 选择一个目标尺寸，这里我们选择最小的那个
    target_size = (min(width1, width2), min(height1, height2))
    # 缩放图片
    img1_resized = img1.resize(target_size, Image.ANTIALIAS)
    img2_resized = img2.resize(target_size, Image.ANTIALIAS)
    return img1_resized, img2_resized


def calculate_ssim(img1, img2):
    img1 = img1.convert('L')
    img2 = img2.convert('L')
    # 如果图片尺寸不同，则调整到相同的尺寸
    if img1.size != img2.size:
        img1, img2 = resize_images(img1, img2)
    # 将图片转换为numpy数组
    img1_array = np.array(img1)
    img2_array = np.array(img2)
    # 计算SSIM
    similarity_index = ssim(img1_array, img2_array)
    return similarity_index


def evaluate_ssim(similarity_index):
    if similarity_index > 0.95:
        return "非常相似"
    elif 0.8 <= similarity_index <= 0.95:
        return "较为相似"
    elif 0.6 <= similarity_index < 0.8:
        return "有一定相似度"
    else:
        return "不相似"